/**
 * 
 */
package com.worksmap.core.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.Order;
import com.taobao.api.request.TradeGetRequest;
import com.taobao.api.request.TradesSoldGetRequest;
import com.taobao.api.response.TradeGetResponse;
import com.taobao.api.response.TradesSoldGetResponse;
import com.worksmap.core.constant.RateConstant;
import com.worksmap.core.dao.TradeDao;
import com.worksmap.core.entity.SellerConfig;
import com.worksmap.core.entity.TaoBaoOrder;
import com.worksmap.core.entity.TaoBaoSeller;
import com.worksmap.core.entity.TaoBaoTrade;
import com.worksmap.core.entity.Trade;
import com.worksmap.core.service.TradeService;
import com.worksmap.core.service.UserService;
import com.worksmap.core.util.JsonUtil;
import com.worksmap.core.util.ObjectUtil;

/**
 * @author jack
 *
 */
@Service
public class TradeServiceImpl implements TradeService {
	
	Logger logger = Logger.getLogger(this.getClass());
	
	@Autowired
	TradeDao tradeDao;
	@Autowired
	UserService userService;

	@Override
	public List<Order> getAllOrderList() {
		return null;
	}

	/**
	 * 返回的json格式："{'trades_sold_get_response':{'has_next':false,'trades':
	 * {'trade':[{'pay_time':'2013-12-15 22:10:49','total_fee':'1000.00'},
	 * {'pay_time':'2013-12-15 21:53:17','total_fee':'1000.00'}]}}}"
	 */
	@Override
	public List<TaoBaoTrade> getSellerNotRateTradeList(TaoBaoSeller seller, Date beginDate, Date endDate){
		List<TaoBaoTrade> tradeList = new ArrayList<TaoBaoTrade>();
		TaobaoClient client = new DefaultTaobaoClient(RateConstant.apiUrl, RateConstant.appkey, RateConstant.appSecret);
    	TradesSoldGetRequest req = new TradesSoldGetRequest();
    	req.setFields(ObjectUtil.getClassFieldStr(TaoBaoTrade.class));       //req.setFields("total_fee,pay_time");  //需要返回的字段
    	req.setStartCreated(beginDate);
    	req.setEndCreated(endDate);
    	req.setStatus("TRADE_FINISHED");    //TRADE_FINISHED（交易成功）
    	/*
    	评价状态，默认查询所有评价状态的数据，除了默认值外每次只能查询一种状态。
    	可选值： RATE_UNBUYER(买家未评) RATE_UNSELLER(卖家未评) RATE_BUYER_UNSELLER(买家已评，卖家未评) 
    	RATE_UNBUYER_SELLER(买家未评，卖家已评) RATE_BUYER_SELLER(买家已评,卖家已评)
    	*/
    	req.setRateStatus("RATE_BUYER_UNSELLER");  
    	req.setPageNo(1L);
    	req.setPageSize(40L);   //每页条数。取值范围:大于零的整数; 默认值:40;最大值:100
    	req.setUseHasNext(true);
    	req.setIsAcookie(false);
    	try {
			TradesSoldGetResponse response = client.execute(req, seller.getAccess_token());
			logger.info("返回的订单list:" + response.getBody());
			JSONObject jsonObject = JSONObject.fromObject(response.getBody());
			String json = "";
			if(jsonObject.containsKey("trades_sold_get_response")){
				json = jsonObject.getString("trades_sold_get_response");
				jsonObject = JSONObject.fromObject(json);
			}
			if(jsonObject.containsKey("trades")){
				json = jsonObject.getString("trades");
				jsonObject = JSONObject.fromObject(json);
			}
			if(jsonObject.containsKey("trade")){
				json = jsonObject.getString("trade");
				tradeList = JsonUtil.parseJsonToList(json, TaoBaoTrade.class);
			}
		} catch (ApiException e) {
			e.printStackTrace();
		}
		return tradeList;
	}
	
	@Override
	public List<Order> getBuyerNotRateOrderList() {
		
		return null;
	}

	@Override
	public boolean saveTrade(Trade trade) {
		if(trade == null){
			return false;
		}
		return tradeDao.saveTrade(trade);
	}
	
	
	/**
	 * 返回的json格式
	 * detail:{"trade_get_response":{"trade":{"orders":{"order":[{"buyer_rate":true,"oid":192329925591084,"seller_rate":true},
	 * 		{"buyer_rate":true,"oid":192329925601084,"seller_rate":true},{"buyer_rate":false,"oid":192329925611084,"seller_rate":true}]}}}}
	 */
	@Override
	public List<TaoBaoOrder> getOrderListByTid(Trade trade) {
		List<TaoBaoOrder> orderList = new ArrayList<TaoBaoOrder>();
		TaoBaoSeller seller = userService.getSellerByNick(trade.getSeller_nick());
		if(seller == null){
			return null;
		}
		TaobaoClient client = new DefaultTaobaoClient(RateConstant.apiUrl, RateConstant.appkey, RateConstant.appSecret);
		TradeGetRequest req=new TradeGetRequest();
		req.setFields("orders.oid,orders.buyer_rate,orders.seller_rate");
		req.setTid(Long.valueOf(trade.getTid()));
		try {
			TradeGetResponse response = client.execute(req, seller.getAccess_token());
			logger.info("返回的订单detail:" + response.getBody());
			JSONObject jsonObject = JSONObject.fromObject(response.getBody());
			String json = "";
			if(jsonObject.containsKey("trade_get_response")){
				json = jsonObject.getString("trade_get_response");
				jsonObject = JSONObject.fromObject(json);
			}
			if(jsonObject.containsKey("trade")){
				json = jsonObject.getString("trade");
				jsonObject = JSONObject.fromObject(json);
			}
			if(jsonObject.containsKey("orders")){
				json = jsonObject.getString("orders");
				jsonObject = JSONObject.fromObject(json);
			}
			if(jsonObject.containsKey("order")){
				json = jsonObject.getString("order");
				orderList = JsonUtil.parseJsonToList(json, TaoBaoOrder.class);
			}
		} catch (ApiException e) {
			e.printStackTrace();
		}
		return orderList;
	}

	@Override
	public boolean updateTrade(Trade trade, String... fields) {
		if(trade == null){
			return false;
		}
		return tradeDao.updateTrade(trade, fields);
	}

	@Override
	public List<Trade> getTradeBySellerConfig(TaoBaoSeller seller,
			SellerConfig sellerConfig) {
		if(seller == null || sellerConfig == null){
			return null;
		}
		return tradeDao.getTradeBySellerConfig(seller, sellerConfig);
	}


}
